//ServerThread.java  
//
//Copyright (C) 2008 Devon Mizelle  
//  
//This program is distributed in the hope that it will be useful,  
//but WITHOUT ANY WARRANTY; without even the implied warranty of  
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
//GNU General Public License for more details.  
//  
//You should have received a copy of the GNU General Public License  
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

package hermes;
import java.io.EOFException;
import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *
 * @author Devon Mizelle
 */
public class ServerThread extends Thread {
    private Socket sock = null;
    private ObjectInputStream ois = null;
    private ObjectOutputStream oos = null;
    private Server server = null;
    public ServerThread(Socket sock, Server server){
        this.sock = sock;   
        this.server = server;
    }
    @Override
    public void run(){
        try{
                ois = new ObjectInputStream(sock.getInputStream());
                oos = new ObjectOutputStream(sock.getOutputStream());
                User user = (User) ois.readObject();
                if(!server.getUserMap().containsKey((String)user.get("id"))){
                    
                    System.out.println(user.get("id") + " has joined the network.");
                    oos.writeObject("Hello " + user.get("id") + " you have been"
                            + " added to the network!");
                    server.addUser(user);
                }
                else{
                    oos.writeObject("Hello " + user.get("id") + "!");
                }
                
                while(true){
                   try{
                       this.sleep(1000);
                       if(ois.available() != 0){
                            String message = (String) ois.readObject();
                   
                            if(message.equals("GET USERMAP")){
                                oos.writeObject(server.getUserMap());
                            }
                       }
                        
                        
                   }
                   catch(java.net.SocketException e){
                       sock.close();
                   }
                   catch(EOFException e){
                        break;
                   }
                   
                }
                
                ois.close();
                oos.close();
                
                
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void sendUserMap(UserMap userMap){
        try{oos.writeObject(userMap);}catch(Exception e){e.printStackTrace();}
    }
}
